package com.lhl.netty.client.ssl;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.security.KeyStore;
import java.security.Security;

public final class SslContextFactory {

    private static final String PROTOCOL = "SSL";
    //private static final String PROTOCOL = "TLS";
    private static final SSLContext CLIENT_CONTEXT;

    static {
        String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
        if (algorithm == null) {
            algorithm = "SunX509";
        }

        SSLContext clientContext;
        try {

            KeyStore trustStore = KeyStore.getInstance("JKS");
            trustStore.load(SslContextFactory.class.getClassLoader().getResourceAsStream("truststore"),"123456".toCharArray());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(trustStore);

            clientContext = SSLContext.getInstance(PROTOCOL);
            clientContext.init(null, tmf.getTrustManagers(), null);
        } catch (Exception e) {
            throw new Error(
                    "Failed to initialize the client-side SSLContext", e);
        }

        CLIENT_CONTEXT = clientContext;
    }

    public static SSLContext getClientContext() {
        return CLIENT_CONTEXT;
    }

    private SslContextFactory() {
        // Unused
    }
}

